<template>
    <view class="payment-container">
        <!-- Header -->
        <view class="header">
            <text class="title">支付收银台</text>
        </view>

        <!-- Amount Display -->
        <view class="amount-section">
            <text class="amount">¥{{orderAmount}}</text>
            <text class="countdown">剩余支付时间: {{countdown}}</text>
        </view>

        <!-- Payment Methods -->
        <view class="payment-methods">
            <view class="payment-method" @click="selectPayment('wechat')">
                <view class="method-left">
                    <image src="/static/icon/weixin.png" class="method-icon"></image>
                    <text class="method-name">微信支付</text>
                </view>
                <radio :checked="selectedMethod === 'wechat'" color="#1AAD19" />
            </view>

            <view class="payment-method" @click="selectPayment('unionpay')">
                <view class="method-left">
                    <image src="/static/icon/银联.png" class="method-icon"></image>
                    <text class="method-name">银联支付</text>
                </view>
                <radio :checked="selectedMethod === 'unionpay'" color="#1AAD19" />
            </view>
        </view>

        <!-- Pay Button -->
        <view class="pay-button-container">
            <button class="pay-button" @click="handlePay">
                立即支付 {{orderAmount}}元
            </button>
        </view>
    </view>
</template>

<script>
export default {
    data() {
        return {
            orderAmount: 0,
            selectedMethod: 'wechat',
            countdown: '29:57',
            timer: null,
            tempOrderData: null
        };
    },
    onLoad() {
        // 获取临时订单数据
        this.tempOrderData = uni.getStorageSync('tempOrderData');
        if (this.tempOrderData) {
            this.orderAmount = this.tempOrderData.totalAmount.toFixed(2);
        }

        // 启动倒计时
        this.startCountdown(29 * 60 + 57); // 29:57 转换为秒数
    },
    onUnload() {
        if (this.timer) {
            clearInterval(this.timer);
        }
    },
    methods: {
        selectPayment(method) {
            this.selectedMethod = method;
        },
        startCountdown(seconds) {
            let remainingSeconds = seconds;
            this.timer = setInterval(() => {
                remainingSeconds--;
                if (remainingSeconds <= 0) {
                    clearInterval(this.timer);
                    // 创建已取消订单
                    this.createOrder('已取消');
                    uni.showModal({
                        title: '支付超时',
                        content: '订单已超时，请重新下单',
                        showCancel: false,
                        success: () => {
                            uni.navigateBack({
                                delta: 2
                            });
                        }
                    });
                    return;
                }
                const minutes = Math.floor(remainingSeconds / 60);
                const secs = remainingSeconds % 60;
                this.countdown = `${minutes}:${secs.toString().padStart(2, '0')}`;
            }, 1000);
        },
        handlePay() {
            uni.showLoading({
                title: '支付中...'
            });
            // 延迟两秒再进行实际的支付操作
            setTimeout(() => {
                // 创建订单，状态为'配送中'
                this.createOrder('配送中');
            }, 2000);
        },
        createOrder(status) {
            const currentPhone = uni.getStorageSync('currentPhone');

            // 生成订单号（使用时间戳作为示例）
            const orderNumber = Date.now().toString();
            // 获取当前支付时间
            const paymentTime = new Date().toISOString();

            // 创建订单对象
            const orderData = {
               ...this.tempOrderData,
                id: Date.now().toString(),
                status: status,
                paymentMethod: this.selectedMethod,
                orderNumber: orderNumber,
                paymentTime: paymentTime
            };

            // 获取所有用户数据
            uni.request({
                url: 'https://67f85eae7719dfcd4b47e8f1.hz-iframe-svc.simplelab.cn/users',
                method: 'GET',
                success: (res) => {
                    if (res.statusCode === 200) {
                        const users = res.data;
                        const currentUser = users.find(user => user.phone === currentPhone);

                        if (currentUser) {
                            // 更新用户的订单数组，将新订单添加到数组开头
                            const updatedUser = {
                               ...currentUser,
                                order: [orderData, ...(currentUser.order || [])]
                            };

                            // 发送更新请求
                            uni.request({
                                url: `https://67f85eae7719dfcd4b47e8f1.hz-iframe-svc.simplelab.cn/users/${currentUser.id}`,
                                method: 'PUT',
                                data: updatedUser,
                                success: (updateRes) => {
                                    uni.hideLoading();
                                    if (updateRes.statusCode === 200) {
                                        // 清除临时订单数据
                                        uni.removeStorageSync('tempOrderData');

                                        if (status === '配送中') {
                                            // 仅在支付成功时清除购物车商品
                                            const allCartItems = uni.getStorageSync('cartItems') || [];
                                            const selectedIds = this.tempOrderData.items.map(item => item._id);
                                            const remainingItems = allCartItems.filter(item =>!selectedIds.includes(item._id));
                                            uni.setStorageSync('cartItems', remainingItems);

                                            uni.showToast({
                                                title: '支付成功',
                                                icon:'success',
                                                duration: 2000
                                            });

                                            // 延迟后导航到订单页面
                                            setTimeout(() => {
                                                uni.switchTab({
                                                    url: '/pages/order/order'
                                                });
                                            }, 2500);
                                        }
                                    } else {
                                        this.showError('订单提交失败');
                                    }
                                },
                                fail: () => {
                                    this.showError('订单提交失败');
                                }
                            });
                        } else {
                            this.showError('用户信息获取失败');
                        }
                    } else {
                        this.showError('获取用户信息失败');
                    }
                },
                fail: () => {
                    this.showError('网络请求失败');
                }
            });
        },
        showError(message) {
            uni.hideLoading();
            uni.showToast({
                title: message,
                icon: 'none'
            });
        }
    }
};
</script>

<style scoped>
.payment-container {
    min-height: 100vh;
    background-color: #f8f8f8;
}

.header {
    background: #0099FF;
    padding: 40rpx 30rpx;
    display: flex;
    align-items: center;
    position: relative;
}

.back-btn {
    position: absolute;
    left: 30rpx;
}

.back-icon {
    color: #fff;
    font-size: 48rpx;
}

.title {
    flex: 1;
    text-align: center;
    color: #fff;
    font-size: 36rpx;
    font-weight: 500;
}

.amount-section {
    background: #0099FF;
    padding: 40rpx;
    display: flex;
    flex-direction: column;
    align-items: center;
    color: #fff;
}

.amount-label {
    font-size: 32rpx;
    margin-bottom: 20rpx;
}

.amount {
    font-size: 72rpx;
    font-weight: bold;
    margin-bottom: 20rpx;
}

.countdown {
    font-size: 28rpx;
    padding: 10rpx 30rpx;
    background: rgba(255, 255, 255, 0.2);
    border-radius: 30rpx;
}

.payment-methods {
    background: #fff;
    margin-top: 20rpx;
    padding: 0 30rpx;
}

.payment-method {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 30rpx 0;
    border-bottom: 1rpx solid #eee;
}

.method-left {
    display: flex;
    align-items: center;
}

.method-icon {
    width: 60rpx;
    height: 60rpx;
    margin-right: 20rpx;
}

.method-name {
    font-size: 32rpx;
    color: #333;
}

.pay-button-container {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    padding: 30rpx;
    background: #fff;
}

.pay-button {
    background: #0099FF;
    color: #fff;
    font-size: 32rpx;
    padding: 20rpx;
    border-radius: 10rpx;
    text-align: center;
    width: 100%;
}
</style>